<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 现金卡类
 * @package  module
 * @subpackage  base/system
 * create by allen.qiang
 * @version 1.0
 */

class quanliCard {

    /**
     * 现金券类型
     */
    private $card_type_array = array(
        '1' => '现金卡',
        '2' => '专享卡'
    );

    /**
     * 查询现金卡详细信息
     * @param array $arg_array 查询参数数组
     * @return null
     */
    public function searchCardDetail( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //代金卡id
        if (isset($arg_array['card_id']) && !empty($arg_array['card_id'])) {
            $sql .= ' AND card_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_id'];
        }

        //现金卡号
        if (isset($arg_array['card_no']) && is_numeric($arg_array['card_no'])) {
            $sql .= ' AND card_no = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_no'];
        }

        //现金卡密码
        if (isset($arg_array['card_pwd']) && !empty($arg_array['card_pwd'])) {
            $sql .= ' AND card_pwd = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['card_pwd']);
        }

        //开始日期
        if(isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
            $sql .= ' AND startDate >= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }

        //结束日期
        if(isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND endDate <= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_detail ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM card_detail ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'timeStamp' => $item->timeStamp,
                    'creator' => $item->creator,
                    'createTime' => $item->createTime,
                    'card_id' => $item->card_id,
                    'card_no' => $item->card_no,
                    'card_name' => $item->card_name,
                    'card_pwd' => decryptD($item->card_pwd),
                    'warehouse_voucher_id' => $item->warehouse_voucher_id,
                    'apply_id' => $item->apply_id,
                    'card_type' => $item->card_type,
                    'face_value_id' => $item->face_value_id,
                    'face_value' => $item->face_value,
                    'discount' => $item->discount,
                    'card_status' => $item->card_status,
                    'can_use_number' => $item->can_use_number,
                    'used_number' => $item->used_number,
                    'good_selector_id' => $item->good_selector_id,
                    'send_card_time' => $item->send_card_time,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'bill_no' => $item->bill_no
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 检查现金卡
     * @param string $card_pwd 现金卡密码
     * @param array $bill_goods_array 订单商品数组
     * @param array $use_card_array 已使用的代金卡数组
     * @param int $bill_no 订单号，默认为空
     * @return array
     */
    public function checkCard( $card_pwd, &$bill_goods_array, &$use_card_array, $bill_no = null ) {

        if (isset($use_card_array['detail'][$card_pwd])) {
            return array('code'=> 400, 'message'=> '现金/专享卡已被使用，请重新输入');
        }

        global $G_SHOP;

        quanli_require('module/base/selector/gSelectorHandler.class.php');
        quanli_require('module/base/selector/custSelector.class.php');

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $G_SHOP->DBCA );

        //查询现金卡信息
        $arg_array = array(
            'card_pwd' => $card_pwd
        );
        $card_array = $this->searchCardDetail( $arg_array );
        if(!$card_array){
            return array('code'=> 400, 'message'=> '现金/专享卡不存在');
        }

        //现金卡信息
        $card_array = $card_array[0];

        $card_type_name = '';

        if($card_array['card_type'] == 1){
            $card_type_name = '现金卡';
        }elseif($card_array['card_type'] == 2){
            $card_type_name = '专享卡';
        }

        if ($card_array['endDate'] < $G_SHOP->sys_date) {
            return array('code'=> 400, 'message'=> $card_type_name.'已失效');
        }

        if ($card_array['startDate'] > $G_SHOP->sys_date) {
            return array('code'=> 400, 'message'=> $card_type_name.'未生效');
        }

        if (in_array($card_array['card_status'], array(1, 2, 3, 4))) {
            return array('code'=> 400, 'message'=> $card_type_name.'不可用');
        }

        if ($card_array['card_status'] == 6) {
            if (empty($card_array['bill_no']) || $card_array['bill_no'] != $bill_no) {
                return array('code'=> 400, 'message'=> $card_type_name.'已被使用');
            }
        }

        if ($card_array['card_status'] == 7) {
            return array('code'=> 400, 'message'=> $card_type_name.'已作废');
        }

        if ($card_array['used_number'] >= $card_array['can_use_number']) {
            if (empty($card_array['bill_no']) || $card_array['bill_no'] != $bill_no) {
                return array('code' => 400, 'message' => $card_type_name.'使用次数已使用完');
            }
        }

        //代金卡剩余面值
        $face_value = $card_array['face_value'];

        $card_goods_array = array();

        //现金券关联城市
        $args_array = array(
            'card_id' => $card_array['card_id']
        );
        $card_city_array = $this->searchCardCity($args_array);

        if(!$card_city_array){
            return array('code'=> 400, 'message'=> $card_type_name.'没有使用城市');
        }

        $city_array = array();
        foreach($card_city_array as $city){
            array_push($city_array, $city['cityID']);
        }

        //循环商品
        foreach( $bill_goods_array as &$goods ){

            //城市过滤
            if(!in_array($goods['cityID'], $city_array)){
                return array('code'=> 400, 'message'=> '商品不在'. $card_type_name .'使用城市范围');
            }

            if(isset($goods['is_buy']) && $goods['is_buy'] == 0)
                continue;
            //筛选商品
            if (!empty($card_array['good_selector_id']) && !$gSelectorHandler->isValid($card_array['good_selector_id'], $goods['postID'])){
                continue;
            }


            /**
             * =============================================
             * 额外购买配件总金额统计
             * $goods['buyFittings'] => 前台额外购买配件数组
             * $goods['fittings'] => 后台额外购买配件数组
             * @author create by allen.qiang
             * =============================================
             */
            $total_fittings_price = 0;  //商品配件总金额变量

            //商品金额和配件总金额
            $goods_price = $goods['price']*$goods['goods_amount']+$total_fittings_price;

            //手动调价
            if(!empty($goods['adjustPrice']) && $goods['adjustPrice'] > -1){
                $goods_price = $goods['adjustPrice']+$total_fittings_price;
            }

            if (!isset($goods['card_deducation'])) {
                $goods['card_deducation'] = 0;
            }

            if( $goods_price == $goods['card_deducation'] ){
                continue;
            }

            //商品剩余可抵扣的金额
            $surplus_card_deducation = $goods_price - $goods['card_deducation'];
            if ($surplus_card_deducation > $face_value ) {
                $goods['card_deducation'] += $face_value;
                $goods['use_card'][$card_pwd] = $face_value;
                $face_value = 0;
            } else {

                $face_value -= $surplus_card_deducation;
                $goods['use_card'][$card_pwd] = $surplus_card_deducation;
                $goods['card_deducation'] += $surplus_card_deducation;
            }

            $card_goods_array[$goods['postID']] = 1;

            if ($face_value == 0) {
                break;
            }

        }

        //代金卡剩余面值 == 代金卡面值， 即未使用，跳出
        error_log($face_value);
        error_log($card_array['face_value']);
        if ($face_value == $card_array['face_value']) {
            return array('code' => 400, 'message' => '没有可抵扣'. $card_type_name .'的商品');
        }

        $use_card_array['balance'] += $face_value;
        $use_card_array['detail'][$card_pwd] = array(
            'card_no' => $card_array['card_no'],
            'card_pwd' => $card_pwd,
            'face_value' => $card_array['face_value'],
            'card_name' => $card_array['card_name'],
            'card_type' => $card_array['card_type'],
            'deducation' => $card_array['face_value'] - $face_value,
            'good_selector_id' => $card_array['good_selector_id'],
            'status' => 1,
            'goods' => $card_goods_array
        );

        return array('code' => 200, 'message' => 'ok', 'data' => $card_pwd);

    }

    /**
     * 查询代金卡面值
     * @param int $face_value_id 面值id
     * @return array|null
     */
    public function searchCardFaceValue( $face_value_id = 0 ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //代金面值id
        if (quanli_is_int($face_value_id)) {
            $sql .= ' AND face_value_id = ?';
            $params_type .= 'i';
            $params_array[] = $face_value_id;
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        $temp_item_array =& $G_SHOP->DBCA->stmt_query('SELECT * FROM card_face_value ' . $sql, $params_type, $params_array);
        if (!$temp_item_array) {
            return null;
        }
        $item_array = array();

        foreach ($temp_item_array as &$item) {
            $item_array[] = array(
                'face_value_id' => $item->face_value_id,
                'face_value' => $item->face_value
            );
        }

        return $item_array;

    }

    /**
     * 回滚已使用的代金卡
     * @param string $card_no 卡号
     * @param int $bill_no 订单号
     * @param int $is_roll_back_used_number 是否回滚使用数量
     * @return array
     */
    public function rollbackCard( $card_no, $bill_no, $is_roll_back_used_number = 0 ) {

        global $G_SHOP;

        if (!isset($card_no, $bill_no) || empty($card_no) || empty($bill_no)) {
            return array('code' => 400, 'message' => '参数错误');
        }

        $card_obj = new entity('card_detail');
        $card_obj->card_no = $card_no;
        if (!$G_SHOP->DBCA->fetch($card_obj)) {
            return array('code' => 404, 'message' => '现金卡信息没有找到');
        }
        $card_obj->card_status = 5;
        $card_obj->bill_no = null;
        if ($is_roll_back_used_number == 1) {
            $card_obj->used_number -= 1;
        }
        $G_SHOP->DBCA->save($card_obj);

        return array('code' => 200, 'message' => '代金卡回滚成功');

    }

    /**
     * 查询现金卡关联城市
     * @param int $arg_array  查询参数数组
     * @return array|null
     */
    public function searchCardCity( $arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //现金卡ID
        if (isset($arg_array['card_id']) && is_numeric($arg_array['card_id'])) {
            $sql .= ' AND card_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_id'];
        }

        //城市ID
        if (isset($arg_array['cityID']) && is_numeric($arg_array['cityID'])) {
            $sql .= ' AND cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //城市名称
        if (isset($arg_array['cityName']) && is_numeric($arg_array['cityName'])) {
            $sql .= ' AND cityName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['cityName'];
        }

        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_city ' . $sql;

                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM card_city ' . $sql;

            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'card_id' => $item->card_id,
                        'cityID' => $item->cityID,
                        'cityName' => $item->cityName
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

}